/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>

*/
package cmd

import (
	"fmt"
	"os"
	"strconv"
	"strings"

	devices "gitee.com/zinface/gpio-ctl/pkg/gpio"
	"github.com/spf13/cobra"
)

// setedgeCmd represents the setedge command
var setedgeCmd = &cobra.Command{
	Use:   "setedge",
	Short: _desc_setedge,
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) > 1 {
			var err error

			// 获取第一个参数
			id, err := strconv.Atoi(args[0])
			if err != nil {
				panic(err)
			}

			// 获取第二个参数
			var edge devices.GPIOEdge
			if strings.Contains(args[1], "none") {
				edge = devices.EDGE_NONE
			} else if strings.Contains(args[1], "rising") {
				edge = devices.EDGE_RISING
			} else if strings.Contains(args[1], "falling") {
				edge = devices.EDGE_FALLING
			} else if strings.Contains(args[1], "both") {
				edge = devices.EDGE_BOTH
			}

			// 尝试写入已导出设备的值
			gpio := devices.NewGPIODevice(id)
			if gpio.IsExported() {
				if edge != "" {
					if err = gpio.ChangeEdge(edge); err != nil {
						panic(err)
					}

					fmt.Printf("SetEdge: gpio%d edge %s success.\n", id, edge)
				} else {
					fmt.Fprintf(os.Stderr, "SetEdge: gpio%d edge '%s' invalid.\n", id, args[1])
				}
			}
		}
	},
}

func init() {
	rootCmd.AddCommand(setedgeCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// setedgeCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// setedgeCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
